<template>
  <el-card>
    <div class="form_body_wrap">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="150px"
        :disabled="isGenerateCode"
      >
        <!-- 商品类型 -->
        <el-row type="flex">
          <el-form-item label="商品类型：" prop="productType">
            <el-select
              class="product_type_select"
              v-model="formData.productType"
              placeholder="请选择"
              @change="handleSelectProductType"
            >
              <el-option
                v-for="item in productTypeOptions"
                :key="item.optionValue"
                :label="item.optionHtml"
                :value="item.optionValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 集散地 是否采集 -->
        <el-row type="flex">
          <el-form-item label="集散地：" prop="disCentre">
            <el-input
              v-model.trim="formData.disCentre"
              placeholder="请输入集散地"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否采集：" prop="centralBuyState">
            <el-radio-group v-model="formData.centralBuyState">
              <el-radio label="1">是</el-radio>
              <el-radio label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 品牌 系列 -->
        <el-row type="flex">
          <el-form-item label="品牌：" prop="brandName">
            <RemoteSelect
              ref="brandRemoteRef"
              placeholder="请选择品牌"
              :optionKeys="['brandName', 'uuid']"
              :echoValue="formData.brandUuid"
              :echoOptions="[formData.brandName, formData.brandUuid]"
              :remoteSelectOptions="remoteOptionsByBrand"
              :handleClickButton="handleChooseBrand"
              @getSelect="getBrandInfoByRemote"
            />
          </el-form-item>
          <el-form-item label="系列：" prop="brandseriesUuid">
            <el-select v-model="formData.brandseriesUuid" placeholder="请选择" v-loading=seriesLoading>
              <el-option
                v-for="item in brandseriesOptions"
                :key="item.seriesUuid"
                :label="item.series"
                :value="item.seriesUuid"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <!-- 商品名称 -->
        <el-row>
          <el-form-item label="商品名称：" prop="productName">
            <el-input
              class="self_lang_input"
              placeholder="请输入商品名称"
              v-model.trim="formData.productName"
              @blur="handleInputProductName"
            >
              <template slot="prepend">{{
                formData.joinBrandName || "暂无品牌"
              }}</template>
            </el-input>
          </el-form-item>
        </el-row>
        <!-- 是否包含品牌 -->
        <el-row>
          <el-form-item label="是否包含品牌：" prop="productNameType">
            <el-radio-group
              v-model="formData.productNameType"
              @change="handleSwitchIsIncludesBrand"
            >
              <el-radio disabled label="1">包含</el-radio>
              <el-radio disabled label="2">不包含</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 商品关键词-别名 -->
        <el-row style="padding-left: 30px;">
          <KeywordsAdd
            ref="keywordRef"
            :dataSource="formData.keywordInfoDTO"
            :productName="getFullProductName()"
            :isDisabled="isGenerateCode"
          />
        </el-row>
        <!-- 助记码 -->
        <el-row>
          <el-form-item label="助记码：" prop="helpCode">
            <el-input
              disabled
              class="self_lang_input"
              v-model.trim="formData.helpCode"
              placeholder="请输入助记码"
              @input="handleVerificationReplaceCn"
            ></el-input>
            <span id="help-code-loading"></span>
          </el-form-item>
        </el-row>
        <!-- 副标题 -->
        <el-row>
          <el-form-item label="副标题：" prop="subtitle">
            <el-input
              class="self_lang_input"
              v-model.trim="formData.subtitle"
              placeholder="请输入副标题"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex">
          <el-form-item label="加价类型：" prop="addPriceType">
            <el-radio-group v-model="formData.addPriceType">
              <el-radio label="1">固定金额</el-radio>
              <el-radio label="2">比例</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 是否采购多计量 -->
        <el-row type="flex">
          <el-form-item label="是否采购多计量：" prop="isPurchaseMultiUnit">
            <el-radio-group
              v-model="formData.isPurchaseMultiUnit"
              @change="handleChangePurchaseMultiUnit"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- 主计量单位 主计量单位小数位 -->
        <el-row type="flex">
          <el-form-item label="主计量单位：" prop="mainUnit">
            <RemoteSelect
              placeholder="请选择主计量单位"
              :optionKeys="['unitName', 'unitUuid']"
              :echoValue="formData.mainUnitUuid"
              :echoOptions="[formData.mainUnit, formData.mainUnitUuid]"
              :remoteSelectOptions="remoteOptionsByUnit"
              :handleClickButton="handleChooseMainUnit"
              @getSelect="(data) => { getUnitByRemote(data, true) }"
            />
          </el-form-item>
          <el-form-item label="主单位小数位：" prop="mainUnitDecimalsStr">
            <el-input-number
              v-model="formData.mainUnitDecimalsStr"
              :min="0"
              :max="3"
              :precision="0"
              controls-position="right"
              placeholder="小数位"
            />
          </el-form-item>
        </el-row>
        <!-- 多计量单位 多计量单位小数位 -->
        <template v-if="isShowSideUnit">
          <el-row>
            <el-form-item
              class="side_unit_title"
              label="添加多计量单位："
            ></el-form-item>
          </el-row>
          <el-row type="flex">
            <el-form-item label="辅计量单位：">
              <RemoteSelect
                placeholder="请选择多计量单位"
                :optionKeys="['unitName', 'unitUuid']"
                :echoValue="formData.sideUnitList.sideUnitUuid"
                :echoOptions="[formData.sideUnitList.sideUnit, formData.sideUnitList.sideUnitUuid]"
                :remoteSelectOptions="remoteOptionsByUnit"
                :handleClickButton="handleChooseMultipleUnit"
                @getSelect="(data) => { getUnitByRemote(data, false) }"
              />
            </el-form-item>
            <el-form-item label="辅计量单位小数位：">
              <el-input-number
                v-model="formData.sideUnitList.sideUnitDecimalsStr"
                :min="0"
                :max="3"
                :precision="0"
                controls-position="right"
                placeholder="小数位"
              />
            </el-form-item>
          </el-row>
        </template>
        <!-- 标签 -->
        <!-- <el-row type="flex">
          <el-form-item label="标签：" prop="tagName">
            <el-input
              v-model="formData.tagName"
              placeholder="请选择标签"
              class="input-with-select"
              :readonly="true"
            >
              <el-button
                slot="append"
                :class="inputBtnClassName"
                @click="handleChooseTag"
                >选择</el-button
              >
            </el-input>
          </el-form-item>
        </el-row> -->
      </el-form>
    </div>
    <!-- 选择品牌弹框 -->
    <SelectBrandDialog
      :visible.sync="visible.brand"
      v-bind="$attrs"
      :canSearchAll="canSearchAllByProductType"
      @getBrandInfo="getBrandInfoByBrandDialog"
    />
    <!-- 选择主计量单位弹框 -->
    <SelectUnitDialog
      :visible.sync="visible.mainUnit"
      :categoryUuid="$attrs.categoryUuid"
      @getUnitInfo="(data) => { getUnitByDialog(data, true) }"
    />
    <!-- 选择多计量（辅计量）单位弹框 -->
    <SelectUnitDialog
      :visible.sync="visible.multipleUnit"
      :categoryUuid="$attrs.categoryUuid"
      @getUnitInfo="(data) => { getUnitByDialog(data, false) }"
    />
    <!-- 选择标签弹框 -->
    <SelectTagDialog
      :visible.sync="visible.tags"
      :tagsList="selectedTagsList"
      @getTagInfo="handleGetTagsData"
    />
  </el-card>
</template>
<script>
import SelectBrandDialog from '@/pages/commodity/components/SelectBrandDialog';
import SelectUnitDialog from '../components/SelectMeasureUnit';
import SelectTagDialog from '@/pages/commodity/components/SelectTagDialog';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import KeywordsAdd from '@/components/KeywordsAdd';
import {
  getBrandInfoListService,
  getUnitUnderCateService,
  getSpuRelSeriesInfoService,
  getHelpCodeInfoService
} from '@/api/commodity/common';
export default {
  props: {
    productTypeOptions: {
      type: Array,
      default () {
        return [];
      }
    },
    isGenerateCode: {
      type: Boolean,
      default: false
    }
  },
  components: {
    SelectBrandDialog,
    SelectUnitDialog,
    SelectTagDialog,
    KeywordsAdd,
    RemoteSelect
  },
  data () {
    return {
      formData: {
        productType: '', // 商品类型
        disCentre: '', // 集散地
        centralBuyState: '2', // 是否采集， 1-是；2-否
        brandName: '', // 品牌
        brandUuid: '',
        hasBarCode: '',
        joinBrandName: '', // 商品名称包含品牌时，所取用的品牌名称
        brandseriesUuid: '', // 系列uuid
        productName: '', // 商品名称
        productNameType: '1', // 名称是否包含品牌， 1-是；2-否
        helpCode: '', // 助记码
        subtitle: '', // 副标题
        addPriceType: '2', // 加价类型, 1-固定金额；2-比例，默认是比例
        isPurchaseMultiUnit: '2', // 是否采购多计量， 1-是；2-否
        mainUnit: '', // 主计量单位
        mainUnitDecimalsStr: 0, // 主单位小数位
        mainUnitUuid: '', // 主计量单位uuid
        // 辅单位关系
        tagName: '', // 标签集合字符串
        tagList: [], // 标签集合
        sideUnitList: {
          scenario: '1', // 应用场景，1采购、2销售
          sideUnit: '', // 辅单位名称
          sideUnitDecimalsStr: 0, // 单位小数位
          sideUnitUuid: '', // 辅单位UUID
          sideUnitNo: ''
        } // 辅单位,选填
      },
      formRules: {
        productType: [{ required: true, message: '商品类型不能为空' }],
        brandName: [{ required: true, message: '品牌不能为空' }],
        productName: [{ required: true, message: '商品名称不能为空' }],
        subtitle: [{ required: true, message: '副标题不能为空' }],
        addPriceType: [{ required: true }],
        isPurchaseMultiUnit: [{ required: true }],
        mainUnit: [{ required: true, message: '主计量单位不能为空' }]
      },
      visible: {
        brand: false,
        mainUnit: false,
        multipleUnit: false,
        tags: false
      },
      brandseriesOptions: [],
      selectedTagsList: [],
      currentUnitType: '1', // 当前计量单位选择弹框对应类型，1为主计量单位，2为辅计量单位
      canSearchAllByProductType: false, // 根据商品类型决定是否可全查品牌，默认不可全查
      seriesLoading: false, // 系列下拉加载loading
    };
  },
  computed: {
    /* 是否展示辅计量单位 */
    isShowSideUnit () {
      return this.formData.isPurchaseMultiUnit === '1'
    },
    /* 复合型输入框禁用按钮样式 */
    inputBtnClassName () {
      let className = this.isGenerateCode ? 'input_button_disabled_color' : 'input_button_color';
      return className;
    }
  },
  methods: {
    // 获取完整商品名称
    getFullProductName () {
      if (this.formData.productNameType === '1') { // 包含品牌名称
        return this.formData.joinBrandName + this.formData.productName;
      }
      if (this.formData.productNameType === '2') { // 不包含品牌名称
        return this.formData.productName;
      }
    },
    // 选择商品类型
    handleSelectProductType () {
      // 切换商品类型清空所选品牌
      this.formData.brandName = '';
      this.formData.brandUuid = '';
      this.formData.joinBrandName = '';
      this.$refs?.brandRemoteRef?.clearOptions && this.$refs.brandRemoteRef.clearOptions()
      this.formData.brandseriesUuid = ''
      this.brandseriesOptions = []
    },
    getGeneratorFormDataFn () {
      const {
        disCentre,
        centralBuyState,
        brandUuid,
        brandName,
        hasBarCode,
        joinBrandName,
        productName,
        productNameType,
        helpCode,
        addPriceType,
        subtitle,
        isPurchaseMultiUnit,
        mainUnit,
        mainUnitDecimalsStr,
        mainUnitUuid,
        tagList,
        sideUnitList
      } = this.formData;
      let generateCodeData = {
        disCentre,
        centralBuyState,
        brandUuid,
        brandName,
        hasBarCode,
        joinBrandName,
        productName,
        productNameType,
        helpCode,
        addPriceType,
        subtitle,
        isSaleMultiUnit: '2', // 是否采销多计量， 1-是；2-否 此功能已废弃，只做默认值传参处理
        isPurchaseMultiUnit,
        mainUnit,
        mainUnitDecimalsStr,
        mainUnitUuid,
        tagList,
      };
      if (isPurchaseMultiUnit !== '2') {
        generateCodeData.sideUnitList = [sideUnitList];
      }
      generateCodeData.addPriceTypeStr =
        addPriceType === '1' ? '固定金额' : '比例';
      /* 商品类型 */
      let productType = _.find(this.productTypeOptions, (item) => {
        return item.optionValue === this.formData.productType;
      });
      if (productType) {
        generateCodeData.productType = productType.optionValue;
        generateCodeData.productTypeStr = productType.optionHtml;
      }
      /* 品牌系列 */
      const brandseriesInfo = this.brandseriesOptions.find(item => item.seriesUuid == this.formData.brandseriesUuid)
      generateCodeData.brandseries = brandseriesInfo?.series
      generateCodeData.brandseriesUuid = brandseriesInfo?.seriesUuid
      /* 单位多计量校验 */
      if (isPurchaseMultiUnit === '1' && !sideUnitList.sideUnit) {
        this.$message.warning('请添加多计量单位');
        return false;
      }
      return generateCodeData;
    },
    // 表单校验
    getFormDataByValidate () {
      return new Promise(resolve => {
        this.$refs.formData.validate(valid => {
          if (!valid) { // 必填校验
            return this.$message.warning('必填项不能为空！');
          }
          resolve(this.getGeneratorFormDataFn());
        });
      });
    },
    // 品牌名称校验：品牌 + 商品名称 长度校验，两者相加不可超过30 --- 可通过助记码长度判断
    validateBrandNameLength (data) {
      const helpCodeLength = data?.helpCode.length || 0;
      const helpCodeLimitLength = 30;
      if (helpCodeLength > helpCodeLimitLength) {
        this.$message.warning(`商品名称与品牌长度之和不能超过${helpCodeLimitLength}`);
        return false;
      }
      return true;
    },
    // 将表单数据转给父组件
    async handleTransferFormData () {
      const validateResult = await this.getFormDataByValidate();
      if (!validateResult) { return false; }
      if (!this.validateBrandNameLength(validateResult)) { return false; }
      const keywordInfoDTO = await this.$refs.keywordRef.getResultBySubmit() || {};
      this.$emit('getFormData', {
        ...validateResult,
        keywordInfoDTO
      });
      return true;
    },
    /* -------------------------------------------- 选择品牌dialog start -------------------------------------------- */
    // 选择品牌
    handleChooseBrand () {
      if (this.formData.productType === '10') { // 如果商品类型是项目商品（10）的时候，品牌可查全部
        this.canSearchAllByProductType = true;
      } else {
        this.canSearchAllByProductType = false;
      }
      this.visible.brand = true;
    },
    // 模糊搜索品牌下拉
    async remoteOptionsByBrand (queryString, loadingFn) {
      const data = {
        nowPage: 1,
        pageShow: 20,
        brandName: queryString,
        categoryUuid: this.formData.productType === '10' ? '' : this.$attrs.categoryUuid,
        notInUuids: ''
      }
      const res = await getBrandInfoListService(data, loadingFn);
      return res?.retData?.results ?? []
    },
    // 获取品牌 by 模糊搜索
    getBrandInfoByRemote (data) {
      this.setBrandInfo({
        name: data.brandName,
        uuid: data.uuid,
        joinBrandName: data.factoryInfluenceMore === '1' ? data.factoryBrandName : data.brandName,
        productNameType: data.productNameType,
        hasBarCode: data.hasBarCode,
        factoryInfluenceMore: data?.factoryInfluenceMore
      });
    },
    // 获取品牌 by 品牌弹框
    getBrandInfoByBrandDialog (brandInfo) {
      this.setBrandInfo(brandInfo);
    },
    // 设置品牌信息
    setBrandInfo (brandInfo) {
      const { name, uuid, joinBrandName, productNameType, hasBarCode, factoryInfluenceMore, factoryBrandName } = brandInfo ?? {}
      if (!factoryInfluenceMore) return this.$message.warning('厂家品牌影响力为空，请维护厂家品牌影响力信息')
      if (factoryInfluenceMore == '1' && !factoryBrandName) return this.$message.warning('当厂家品牌影响力大于品牌时，厂家品牌名称不能为空')
      this.formData.brandName = name;
      this.formData.brandUuid = uuid;
      this.formData.joinBrandName = joinBrandName;
      this.formData.productNameType = productNameType;
      this.formData.hasBarCode = hasBarCode;
      this.getBrandseriesOptions(uuid); // 获取系列下拉options
      if (this.formData.productName) { // 如果有品牌名称，再获取一次助记码
        this.getFormHelpCode();
      }
    },
    /* -------------------------------------------- 选择品牌dialog end -------------------------------------------- */
    /* 获取品牌系列下拉内容action */
    async getBrandseriesOptions (brandUuid) {
      const data = {
        categoryUuid: this.$attrs.categoryUuid,
        brandUuid,
        productType: this.formData.productType
      }
      const loadingFn = state => { this.seriesLoading = state }
      const res = await getSpuRelSeriesInfoService(data, loadingFn)
      if (res?.retData) {
        this.brandseriesOptions = res.retData ?? []
        this.brandseriesOptions.length == 1 && this.$set(this.formData, 'brandseriesUuid', this.brandseriesOptions[0].seriesUuid) // 品牌下只有一个系列，自动代入该系列
      }
    },
    /* -------------------------------------------- 计量单位dialog start -------------------------------------------- */
    // 选择主计量单位
    handleChooseMainUnit () {
      this.visible.mainUnit = true;
    },
    // 选择多计量（辅计量）单位
    handleChooseMultipleUnit () {
      this.visible.multipleUnit = true;
    },
    // 获取计量单位查询入参
    getUnitSearchParams (unitName) {
      return {
        nowPage: 1,
        pageShow: 20,
        unitName,
        categoryUuid: this.$attrs.categoryUuid
      }
    },
    // 计量单位模糊搜索
    async remoteOptionsByUnit (queryString, loadingFn) {
      const data = this.getUnitSearchParams(queryString);
      const res = await getUnitUnderCateService(data, loadingFn)
      return res?.retData?.results ?? []
    },
    // 获取模糊搜索计量单位
    getUnitByRemote (data, isMainUnit) {
      this.setUnitData(data, isMainUnit);
    },
    // 获取弹框选择的计量单位
    getUnitByDialog (data, isMainUnit) {
      this.setUnitData(data, isMainUnit);
    },
    // 设置计量单位
    setUnitData (unitInfo, isMainUnit) {
      const { unitName, unitNo, decimalPlaces, unitUuid } = unitInfo ?? {}
      if (isMainUnit) { // 是主计量单位
        this.formData.mainUnit = unitName;
        this.formData.mainUnitUuid = unitUuid;
        this.formData.mainUnitDecimalsStr = decimalPlaces;
      } else { // 是多计量（辅计量）单位
        this.formData.sideUnitList.sideUnit = unitName;
        this.formData.sideUnitList.sideUnitUuid = unitUuid;
        this.formData.sideUnitList.sideUnitNo = unitNo;
        this.formData.sideUnitList.sideUnitDecimalsStr = decimalPlaces;
      }
    },
    /* -------------------------------------------- 计量单位dialog end -------------------------------------------- */
    /* 选择标签事件 */
    handleChooseTag () {
      this.visible.tags = true;
    },
    /* 获取选择的标签数据事件 */
    handleGetTagsData (tagsList) {
      let tagNameList = [];
      this.selectedTagsList = tagsList;
      this.formData.tagList = tagsList.reduce((value, item) => {
        tagNameList.push(item.labelName);
        value.push({
          tagName: item.labelName,
          tagUuid: item.uuid
        });
        return value;
      }, []);
      this.formData.tagName = tagNameList.join(',');
    },
    /* 检测助记码是否有输入中文事件，输入中文就替换为空 */
    handleVerificationReplaceCn () {
      let replaceCode = _.replace(
        this.formData.helpCode,
        /[\u4E00-\u9FA5]/g,
        ''
      );
      this.$set(this.formData, 'helpCode', replaceCode);
    },
    /* 输入商品名称的失焦事件 */
    handleInputProductName () {
      if (!this.formData.joinBrandName || !this.formData.productName) {
        this.$set(this.formData, 'helpCode', '');
        return false;
      }
      this.getFormHelpCode();
    },
    /* 切换是否包含品牌事件 */
    handleSwitchIsIncludesBrand () {
      const boolList = {
        '1': this.formData.joinBrandName && this.formData.productName,
        '2': this.formData.productName
      }
      const boolFlag = boolList[this.formData.productNameType];
      if (!boolFlag) {
        this.$set(this.formData, 'helpCode', '');
        return false;
      }
      this.getFormHelpCode();
    },
    // 获取表单助记码
    async getFormHelpCode () {
      const { joinBrandName, productName, productNameType, productType } = this.formData;
      const data = {
        productType,
        productNameType,
        productName,
        brandName: joinBrandName,
      };
      const retData = await getHelpCodeInfoService(data, '.form_body_wrap');
      if (retData) {
        this.$set(this.formData, 'helpCode', retData.helpCode);
      }
    },
    /*
      改变采购多计量状态，此状态决定进价是否是多计量
      采购多计量级别小于采销多计量，但是会反向影响采销多计量的状态
      当采购和采销都为多计量时，切换采购为单计量，采销也随之变化为单计量
    */
    handleChangePurchaseMultiUnit (val) {
      /* 是采购多计量，但不是采销多计量 */
      if (val === '1') {
        this.formData.sideUnitList.scenario = '1';
      }
    },
    /*
      改变采销多计量状态，此状态决定售价是否是多计量
      采销多计量级别小于采销多计量，所以会影响采销多计量的状态，当采销为多计量时，采购也变更为多计量
      单计量不受影响
    */
    handleChangeSaleMultiUnit (val) {
      /* 是采销多计量 */
      if (val === '1') {
        this.formData.sideUnitList.scenario = '2';
        this.formData.isPurchaseMultiUnit = '1';
      }
    },
  }
};
</script>
<style lang="less" scoped>
.form_body_wrap {
  padding-left: 150px;
  /* 商品类型下拉框样式 */
  .product_type_select {
    /deep/ .el-input__inner {
      width: 300px;
    }
  }
  .input_button_color {
    color: #ffffff;
    background-color: #5a9cf8;
  }
  .input_button_disabled_color {
    color: #dbdee3;
  }
  .el-button.is-disabled:hover {
    border-top: #f4f6f9;
    background-color: #f4f6f9;
  }
  /* 多计量标题样式 */
  .side_unit_title {
    /deep/ .el-form-item__label {
      font-weight: 900;
    }
  }
  /* 多计量-辅计量单位删除按钮样式 */
  .side_unit_del_btn {
    margin-left: 20px;
  }
  /* 商品名称输入框样式 */
  .self_lang_input {
    width: 60%;
  }
}
</style>
